<template>
  <div class="dashboard-container">
    <div class="app-container">
      <Page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="AddEmployee">新增员工</el-button>
        </template>
      </Page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                slot="reference"
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" :formatter="formatEmployment" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <!-- 作用域插槽 -->
            <template slot-scope="{ row }">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button v-if="checkPermission('POINT-USER-UPDATE')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssignDialogFn(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="page.size" :total="total" :current-page="page.page" @current-change="changePage" />
        </el-row>
      </el-card>
    </div>
    <addEmployee :show-dialog.sync="showDialog" @addEmployee="getEmploeeList" />
    <!-- 点击员工头像，生成二维码 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="showCodeDialog=false">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <assignRole ref="assignRole" :show-role-dialog.sync="showAssignDialog" />
  </div>
</template>

<script>
import addEmployee from '@/views/employees/components/addEmployee.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import EmployeeEnum from '@/api/constant/employees'
import { getEmploeeList, delEmployee } from '@/api/emploees'
import PageTools from '@/components/PageTools/index.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import assignRole from '@/views/employees/components/assign-role.vue'

export default {
  components: {
    PageTools,
    addEmployee,
    assignRole
  },

  data() {
    return {
      page: {
        page: 1,
        size: 6

      },
      total: 0,
      list: [],
      showDialog: false,
      showCodeDialog: false,
      imgUrl: '',
      showAssignDialog: false,
      userId: ''

    }
  },
  created() {
    this.getEmploeeList()
  },
  methods: {
    // 给员工添加角色
    async showAssignDialogFn(id) {
      await this.$refs.assignRole.getUserId(id)
      this.showAssignDialog = true

      // this.userId = id
    },

    // 回显员工角色数据
    // 添加新员工
    AddEmployee() {
      this.showDialog = true
    },

    // 1.获取员工数据
    // 导出员工列表
    async exportExcel() {
      const { rows } = await getEmploeeList({ page: this.page.page, size: this.total })
      console.log(rows)
      // 2.数据转换。对象转数组
      const data = rows.map(userObj => {
        return this.objToArray(userObj)
      })
      console.log(85, data)
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职时间']
      // 3. 生成excel
      export_json_to_excel({
        header,
        data
      })
    },

    // 对象转数组封装
    objToArray(userObj) {
      const userArray = []
      const zidian = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      }
      // 遍历字典，每个key都拿出英文字段，去用户对象获取数据
      // 推入数组中，最终可以形成顺序的用户数组
      for (const key in zidian) {
        const enKey = zidian[key]
        const value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find(item => Number(item.id) === Number(value))
          userArray.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry') {
          userArray.push(formatDate(value))
        } else {
          userArray.push(value)
        }
      }
      console.log(111, userArray)
      return userArray
    },

    async getEmploeeList() {
      const { rows, total } = await getEmploeeList(this.page)
      // const list = await getEmploeeList(this.page)
      // 造假数据
      this.list = rows.map(user => {
        const state = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || state
        }
      })
      this.total = total
      // console.log(67, this.list)
    },

    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find(item => Number(item.id) === Number(cellValue))
      return obj ? obj.value : '未知'
    },

    // 实现翻页功能
    changePage(newPage) {
      this.page.page = newPage
      this.getEmploeeList()
    },

    // 删除员工列表
    async delEmployee(id) {
      await this.$confirm('确定删除')
      await delEmployee(id)
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page = this.page.page - 1
        // this.getEmploeeList()
      }
      this.$message.success('删除成功')
      this.getEmploeeList()
    },

    // 点击图片显示二维码，需要带参数url
    showQrCode(url) {
      // 如果存在url，就是用户是有头像的，在显示弹框
      if (url) {
        this.showCodeDialog = true
        // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 需要用到数据更新完毕之后，才渲染数据，$nextTick
        this.$nextTick(() => {
          // 将地址转换成为二维码
          QrCode.toCanvas(this.$refs.myCanvas, url)
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户未上传头像')
      }

      // console.log(193, url)
    }

  }
}
</script>

<style>

</style>
